package com.haiertvbic.tvnow.network;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.xmlpull.v1.XmlPullParser;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Xml;

import com.haiertvbic.tvnow.R;
import com.haiertvbic.tvnow.db.DbAdapter;
import com.haiertvbic.tvnow.model.Actor;
import com.haiertvbic.tvnow.model.ProgramDetail;
import com.haiertvbic.tvnow.model.ProgramItem;
import com.haiertvbic.tvnow.model.ProgramOTT;
import com.haiertvbic.tvnow.model.ScreenShot;
import com.haiertvbic.tvnow.model.ThridProgram;
import com.haiertvbic.tvnow.model.UpdateInfo;
import com.haiertvbic.tvnow.network.paser.ActorPaser;
import com.haiertvbic.tvnow.network.paser.ActorsPaser;
import com.haiertvbic.tvnow.network.paser.FilterItemPaser;
import com.haiertvbic.tvnow.network.paser.LiveEpgPaser;
import com.haiertvbic.tvnow.network.paser.OTTPaser;
import com.haiertvbic.tvnow.network.paser.ProductsPaser;
import com.haiertvbic.tvnow.network.paser.ProgramPaser;
import com.haiertvbic.tvnow.network.paser.UpdateInfoPaser;
import com.haiertvbic.tvnow.protocol.CAEProtocol;
import com.haiertvbic.tvnow.util.Constant;
import com.haiertvbic.tvnow.util.SLog;
import com.haiertvbic.tvnow.util.TimeUtil;

public class EPGWeb {
	private static final String TAG = "EPGWeb";
	public static String epgUrl = "http://cipwebsvc.haierusp.com/haier_ci_service";
	private static String testOttUrl = "http://210.51.17.75:8080/EPG-OTT/GetWebServlet";
	private static String actroUrl = "http://210.51.17.77:8080/sscepg/haiersscepg";
	public static final int SYS_TIME_ERROR = 20000;
	public static final int SERVER_TIME_ERROR = 20001;
	public static final int SERVER_PTYPE_NOT_SUITABLE = 20002;
	public static final int SERVER_NO_DATA = 20003;
	public static final int SERVER_REQUEST_OUTIME = 20004;
	public static final int NO_NETWORK = 20007;
	public static final int DATA_SUC = 20009;
	public static final int STORAGE_LOW = 20006;
	public static final int OTT_NAME_ENCODING_ERROR = 20008;

	/**
	 * 演员信息
	 * 
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static Actor getActorInfo(Context context, String actorPid) {
		// http://cipwebsvc.haierusp.com/haier_ci_service?serviceno=4040&serviceauth=服务授权码&sid=随机会话编号&devmac=md5mac&devtype=设备类型号&epgflag=11&id=818
		Map<String, String> parmas = new HashMap<String, String>();
		parmas.put("serviceno", "4040");
		setParmas(parmas);

		parmas.put("epgflag", "11");
		parmas.put("id", actorPid);
		WebData cloudData = new WebData(epgUrl);
		InputStream result = null;
		try {
			result = cloudData.PostDataStream(parmas);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Actor actor = null;
		if (result != null) {
			actor = new ActorPaser(result).getContent();
		}
		return actor;

	}

	private static void setParmas(Map<String, String> parmas) {
		parmas.put("serviceauth", "haiertv");
		parmas.put("sid", "123456");
		parmas.put("devmac", Constant.MAC);
		parmas.put("devtype", "DC18F0M0200A");
	}

	/**
	 * 节目的演员信息
	 * 
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static ArrayList<Actor> getActorsInfo(Context context, String pid) {
		// http://cipwebsvc.haierusp.com/haier_ci_service?serviceno=4040&serviceauth=服务授权码&sid=随机会话编号&devmac=md5mac&devtype=设备类型号&epgflag=10&id=01774eba55461417887733df822f1b8b
		Map<String, String> parmas = new HashMap<String, String>();
		parmas.put("serviceno", "4040");

		setParmas(parmas);

		parmas.put("epgflag", "10");
		parmas.put("id", pid);
		WebData cloudData = new WebData(epgUrl);
		InputStream result = null;
		try {
			result = cloudData.PostDataStream(parmas);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ArrayList<Actor> actors = null;
		if (result != null) {
			actors = new ActorsPaser(result).getContent();
		}
		return actors;
	}

	public static ArrayList<ProgramDetail> getActorProducts(Activity context,
			String starName) {
		// http://210.51.17.77:8080/sscepg/haiersscepg?epgflag=12&starName=赵
		Map<String, String> parmas = new HashMap<String, String>();
		parmas.put("epgflag", "12");
		parmas.put("starName", starName);
		WebData cloudData = new WebData(actroUrl);
		InputStream result = null;
		try {
			result = cloudData.PostDataStream(parmas);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ArrayList<ProgramDetail> programs = null;
		if (result != null) {
			programs = new ProductsPaser(result).getContent();
		}
		return programs;
	}

	/**
	 * 得到网络资源
	 * 
	 * @param context
	 * @param pname
	 * @param js
	 * @param pType
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static ProgramOTT getOttList(Context context, String pname,
			String js, String pType) throws ClientProtocolException,
			IOException {
		// http://210.51.17.76:8080/EPG-OTT/GetWebServlet?serviceno=4041&serviceauth=11111&sid=1111&devmac=md5mac&devtype=1111&pname=%E8%8A%82%E6%8C%AF%E5%9B%BD%E4%BC%A0%E5%A5%87&classID=92&js=0
		ProgramOTT programOtt = new ProgramOTT();
		try {
			pname = java.net.URLEncoder.encode(pname, "utf-8");
			SLog.d(TAG, "pname===" + pname);
		} catch (UnsupportedEncodingException e) {
			SLog.i(TAG, e.toString());
		}
		Map<String, String> parmas = new HashMap<String, String>();

		parmas.put("serviceno", "4041");
		setParmas(parmas);

		parmas.put("pname", pname);
		parmas.put("js", js);
		parmas.put("classID", pType);
		WebData cloudData = new WebData(testOttUrl);
		InputStream result = cloudData.PostDataStream(parmas);
		if (result != null) {
			programOtt = new OTTPaser(result).getContent();
		}
		return programOtt;
	}

	/**
	 * 是否更新应用
	 * 
	 * @return
	 */
	public static UpdateInfo getUpdateInfo(Context context) {
		// http://cipwebsvc.haierusp.com/haier_ci_service?serviceno=7010&serviceauth=haiertv&sid=haiersid&devmac=md5mac&devtype=DC18F0M0200A&lang=1&platform=mst6a600&locid=1&package=com.haiertvbic.tvnow&versionCode=1&versionName=1.1
		Map<String, String> parmas = new HashMap<String, String>();
		parmas.put("serviceno", "7010");

		setParmas(parmas);
		String language = context.getString(R.string.language);
		parmas.put("lang", language);
		parmas.put("platform", Constant.TvPlatform);
		String localCode = "110000";
		try {
			localCode = CAEProtocol.getLocalCode().getCity() + "";
		} catch (Exception e) {
		}
		parmas.put("locid", localCode);

		PackageManager pm = context.getPackageManager();
		PackageInfo pinfo = null;
		try {
			pinfo = pm.getPackageInfo(context.getPackageName(), 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		parmas.put("package", pinfo.packageName);
		parmas.put("versionCode", pinfo.versionCode + "");
		parmas.put("versionName", pinfo.versionName);

		WebData cloudData = new WebData(epgUrl);
		InputStream result = null;
		try {
			result = cloudData.PostDataStream(parmas);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		UpdateInfo update = new UpdateInfo();
		if (result != null) {
			update = new UpdateInfoPaser(result).getContent();
		}
		return update;
	}

	/**
	 * 得两天倒节目列表，并存储到数据库
	 * 
	 * @param context
	 * @param channelId
	 *            所得节目列表的频道号
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static ArrayList<ProgramDetail> getProgramList(Context context,
			String channelId) throws ClientProtocolException, IOException {
		// http://cipwebsvc.haierusp.com/haier_ci_service?serviceno=4040&serviceauth=haiertv&sid=123456&devmac=d41d8cd98f00b204e9800998ecf8427e&devtype=DC18F0M0200A&epgflag=5&ctype=1&cid=46&epic=0&type=day&value=2
		Map<String, String> parmas = new HashMap<String, String>();
		parmas.put("serviceno", "4040");

		setParmas(parmas);

		parmas.put("epgflag", "5");
		parmas.put("ctype", 1 + "");
		parmas.put("cid", channelId);
		parmas.put("epic", 0 + "");// 表示不要默认界面图片2013-2-19日加
		parmas.put("type", "day");
		parmas.put("value", 2 + "");

		ArrayList<ProgramDetail> programs = getProgramFormNET(context, parmas);
		if (programs != null && programs.size() > 0) {
			DbAdapter dbdata = new DbAdapter();
			dbdata.getInstance(context);
			try {
				dbdata.addPrograms(programs);
			} catch (Exception e) {
				// 存储不成功,内存不够
				SLog.d(TAG, "====" + e.toString());
			}
		}
		return programs;
	}

	/**
	 * 跨频道搜索，每次都从网络请求
	 * 
	 * @param context
	 * @param pid
	 *            节目的唯一标识
	 * @param code
	 *            该电视机所在的区域码
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static ArrayList<ProgramDetail> getSituation(Context context,
			String pid, String code) throws ClientProtocolException,
			IOException {
		// http://cipwebsvc.haierusp.com/haier_ci_service?serviceno=4040&serviceauth=服务授权码&sid=随机会话编号&devmac=md5mac&devtype=设备类型号&searchtype=4&fid=be4c17002fac911b106c3e7242cd9622&locid=1&type=day&value=2
		Map<String, String> parmas = new HashMap<String, String>();

		parmas.put("serviceno", "4040");

		setParmas(parmas);

		parmas.put("searchtype", "4");
		parmas.put("fid", pid);
		parmas.put("locid", code);// 1
		parmas.put("type", "day");
		parmas.put("value", 2 + "");
		ArrayList<ProgramDetail> programs = getProgramFormNET(context, parmas);
		// 取当前时间以下的节目返回
		if (programs != null && programs.size() > 0) {
			programs = TimeUtil.filterByTime(programs);
		}
		return programs;
	}

	public static ArrayList<ProgramDetail> getCurrentProgram(Context context,
			String cid) {
		// http://cipwebsvc.haierusp.com/haier_ci_service?serviceno=4040&serviceauth=haiertv&sid=123456&devmac=123456&devtype=DC18F0M0200A&searchtype=11&cid=频道id
		Map<String, String> parmas = new HashMap<String, String>();
		parmas.put("serviceno", "4040");

		setParmas(parmas);

		parmas.put("searchtype", "11");
		parmas.put("cid", cid);
		ArrayList<ProgramDetail> program = null;
		try {
			program = getProgramFormNET(context, parmas);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return program;
	}

	/**
	 * 从网络得节目分类，并存储到数据库
	 * 
	 * @param context
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static ArrayList<ProgramItem> getItems(Context context) {
		// http://cipwebsvc.haierusp.com/haier_ci_service?serviceno=4040&serviceauth=服务授权码&sid=随机会话编号&devmac=md5mac&devtype=设备类型号&searchtype=12
		Map<String, String> parmas = new HashMap<String, String>();
		parmas.put("serviceno", "4040");

		setParmas(parmas);

		parmas.put("searchtype", "12");
		WebData cloudData = new WebData(epgUrl);
		InputStream result = null;
		try {
			result = cloudData.PostDataStream(parmas);
		} catch (ClientProtocolException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		ArrayList<ProgramItem> items = null;
		if (result != null) {
			items = new FilterItemPaser(result).getContent();
			DbAdapter dbdata = new DbAdapter();
			dbdata.getInstance(context);
			try {
				dbdata.addProgramItem(items);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		return items;

	}

	/**
	 * 网络取图，
	 * 
	 * @param context
	 * @param cid
	 * @param count
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static ArrayList<ScreenShot> getChannelPIPXML(Context context,
			String cid, int count) throws ClientProtocolException, IOException {
		// http://cipwebsvc.haierusp.com/haier_ci_service?serviceno=7000&serviceauth=haiertv&sid=123456&devmac=md5mac&devtype=DC18F0M0200A&NUM=1&channelID=6
		Map<String, String> parmas = new HashMap<String, String>();
		parmas.put("serviceno", "7000");

		setParmas(parmas);

		parmas.put("resolution", "2");
		parmas.put("NUM", count + "");
		// parmas.put("NUM", "0");
		parmas.put("channelID", cid);

		WebData cloudData = new WebData(epgUrl);
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("haierFlag", ImageUtil.haierFlag);
		headers.put("offset ", ImageUtil.offset);
		cloudData.setHeader(headers);
		InputStream result = cloudData.PostDataStream(parmas);

		ArrayList<ScreenShot> screenShots = null;
		if (result != null) {
			screenShots = new LiveEpgPaser(result).getContent();
			HttpResponse response = cloudData.getHeader();
			if (response != null) {
				if (response.getHeaders("haierFlag").length > 0) {
					ImageUtil.haierFlag = response.getHeaders("haierFlag")[0]
							.getValue();
				}
				if (response.getHeaders("offset").length > 0) {
					ImageUtil.offset = response.getHeaders("offset")[0]
							.getValue();
				}
			}
		}
		return screenShots;
	}

	/**
	 * 
	 * @param channelId
	 * @param number
	 * @param picID
	 * @param slide
	 *            参数有二,right表示取新图,left表示取老图,不传表示去老图
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static String getPIPString(String channelId, int number,
			String picID, String slide) {
		// http://cipwebsvc.haierusp.com/haier_ci_service?serviceno=7000&serviceauth=haiertv&sid=123456&devmac=md5mac&devtype=DC18F0M0200A&NUM=5&channelID=1&resolution=2&slide=&picID=3_365x205_1383550010000
		Map<String, String> parmas = new HashMap<String, String>();
		parmas.put("serviceno", "7000");

		setParmas(parmas);

		parmas.put("resolution", "2");
		parmas.put("slide", slide);
		parmas.put("NUM", number + "");
		parmas.put("channelID", channelId);
		parmas.put("picID", picID);

		WebData cloudData = new WebData(epgUrl);
		InputStream result = null;
		try {
			result = cloudData.PostDataStream(parmas);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String str = null;
		if (result != null) {
			str = cloudData.convertStreamToString(result);
		}
		return str;
	}

	public static void uploadXinLangInfor(Context context, String userInfor) {
		// http://cipwebsvc.haierusp.com/haier_ci_service?serviceno=6200&serviceauth=haiertv&sid=123456&devmac=md5mac&op=GetUserInfo&platform=6a801&info=6
		Map<String, String> parmas = new HashMap<String, String>();
		parmas.put("serviceno", "6200");

		setParmas(parmas);

		parmas.put("op", "GetUserInfo");
		parmas.put("platform", "6a801");
		parmas.put("info", userInfor);

		WebData cloudData = new WebData(epgUrl);

		try {
			InputStream result = cloudData.PostDataStream(parmas);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据所传路径解析第三方节目资源
	 * 
	 * @param moreUrl
	 * @return
	 */
	public static ArrayList<ThridProgram> paserThridProgram(String moreUrl) {
		ArrayList<ThridProgram> thridPrograms = null;
		try {
			URL url1 = new URL(moreUrl);
			HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
			conn.setConnectTimeout(6 * 1000);
			if (conn.getResponseCode() != 200) {
				return null;
			}
			InputStream result = conn.getInputStream();

			// =============================================
			XmlPullParser parser = Xml.newPullParser();
			ThridProgram thridProgram = null;
			try {
				parser.setInput(result, "UTF-8");
				int eventType = parser.getEventType();
				while (eventType != XmlPullParser.END_DOCUMENT) {

					switch (eventType) {
					case XmlPullParser.START_DOCUMENT:// 文档开始事件,可以进行数据初始化处理
					case XmlPullParser.START_TAG:// 开始元素事件
						String parserName = parser.getName();
						if ("apk".equals(parser.getName())) {
							thridPrograms = new ArrayList<ThridProgram>();
						} else if ("third_page".equals(parser.getName())) {
							thridPrograms = new ArrayList<ThridProgram>();
						} else if ("p".equals(parser.getName())) {
							thridProgram = new ThridProgram();
						} else if ("name".equals(parser.getName())) {
							thridProgram.setName(parser.nextText());
						} else if ("pid".equals(parser.getName())) {
							thridProgram.setPid(parser.nextText());
						} else if ("js".equals(parser.getName())) {
							thridProgram.setJs(parser.nextText());
						} else if ("link".equals(parser.getName())) {
							thridProgram.setLink(parser.nextText());
						} else if ("type".equals(parser.getName())) {
							thridProgram.setType(parser.nextText());
						}

						break;
					case XmlPullParser.END_TAG:// 结束元素事件
						if ("p".equals(parser.getName())) {
							thridPrograms.add(thridProgram);
						}
						break;
					}
					eventType = parser.next();
				}
			} catch (Exception e) {
				SLog.i(TAG, e.toString());
				return null;
			} finally {
				try {
					if (result != null) {
						result.close();
					}
				} catch (IOException e) {
					SLog.i(TAG, e.toString());
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return thridPrograms;

	}

	/**
	 * 
	 * @param context
	 * @param parmas
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	private static ArrayList<ProgramDetail> getProgramFormNET(Context context,
			Map<String, String> parmas) throws ClientProtocolException,
			IOException {

		WebData cloudData = new WebData(epgUrl);
		InputStream result = cloudData.PostDataStream(parmas);

		ArrayList<ProgramDetail> programs = new ArrayList<ProgramDetail>();
		if (result != null) {
			programs = new ProgramPaser(result).getContent();
		}

		return programs;
	}

	/**
	 * 根据URL获取图片：先根据URL中图片的文件名获取本地，若本地没有则根据URL获取网络
	 * 
	 * @param urlString
	 * @return
	 */
	public static Bitmap getBitmapFromURL(Context context, String urlString) {
		Bitmap bm = null;
		// http://210.51.17.76:8080/epgpic/79005_120.jpg
		String cacheDir = context.getFilesDir().getParent() + "/cache/";
		String[] s = urlString.split("/");
		String path = cacheDir + s[s.length - 1];
		// mnt/sdcard/package/79005_120_2012_03_28.jpg
		File mfile = new File(path);
		File file = new File(cacheDir);
		file.listFiles();
		if (mfile.exists()) { // 若该文件存在
			bm = BitmapFactory.decodeFile(path);
		} else {
			if (NetUtil.getNetworkInfo(context)) {
				bm = ImageUtil.getPicData(urlString);
				if (bm != null) {
					saveCache(bm, path);
				}
			}
		}
		return bm;
	}

	/**
	 * 按属性过滤传来的节目
	 * 
	 * @param programPackage
	 * @param context
	 * @return
	 */
	public static ArrayList<ProgramDetail> filterByAttribute(
			ArrayList<ProgramDetail> programs, Context context) {

		DbAdapter dbdata = new DbAdapter();
		dbdata.getInstance(context);
		ArrayList<ProgramItem> items = dbdata.findAllProgramItem();
		if (items == null) {
			items = getItems(context);
		}
		ArrayList<ProgramDetail> programsTemp = new ArrayList<ProgramDetail>();
		for (int proCount = 0; proCount < programs.size(); proCount++) {
			String proTypes = programs.get(proCount).getPtype();
			if (proTypes.trim().length() > 0) {
				String[] proType = proTypes.split(",");
				for (int typeCount = 0; typeCount < proType.length; typeCount++) {
					for (int j = 0; items != null && j < items.size(); j++) {
						String itemType = items.get(j).getNode();
						if (proType[typeCount].equals(itemType)) {
							programsTemp.add(programs.get(proCount));
							break;
						}
					}
					if (programsTemp.contains(programs.get(proCount))) {
						break;
					}
				}

			}

		}
		return programsTemp;
	}

	/**
	 * 将图片保存到SD卡
	 * 
	 * @param bm
	 * @param filename
	 */
	private static void saveCache(Bitmap bm, String filename) {
		SLog.d(TAG, "文件名为=====" + filename);
		try {
			File myCaptureFile = new File(filename);
			BufferedOutputStream bos;
			bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
			bm.compress(Bitmap.CompressFormat.PNG, 80, bos);
			bos.flush();
			bos.close();
		} catch (FileNotFoundException e) {
			if (e != null) {
				SLog.e(TAG, e.getMessage());
			}
		} catch (IOException e) {
			if (e != null) {
				SLog.e(TAG, "-------" + e.getMessage());
			}
		} catch (Exception e) {
			// sd卡满了，写不进去
		}

	}

}
